package com.ruoyi.energy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.mysql.cj.x.protobuf.MysqlxResultset;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.energy.domain.QyEnterprise;
import com.ruoyi.energy.domain.QyEnterpriseType;
import com.ruoyi.energy.domain.vo.EnterpriseExcelVO;
import com.ruoyi.energy.mapper.AllFeeProjectMapper;
import com.ruoyi.energy.mapper.QyEnterpriseMapper;
import com.ruoyi.energy.service.IQyEnterpriseService;
import com.ruoyi.energy.service.IQyEnterpriseTypeService;
import com.ruoyi.omp.api.RemoteCustomerService;
import com.ruoyi.omp.api.RemoteLeaseRecordService;
import com.ruoyi.omp.api.RemoteRoomService;
import com.ruoyi.omp.api.RemoteSuretyService;
import com.ruoyi.omp.api.domain.*;
import com.ruoyi.omp.api.domain.vo.EnterpriseVo;
import com.ruoyi.omp.api.domain.vo.RoomVO;
import com.ruoyi.system.api.LinkFileServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.List;

/**
 * 企业概况Service业务层处理
 *
 * @author cjie
 * @date 2021-08-02
 */
@Service
@Slf4j
public class QyEnterpriseServiceImpl extends LinkFileServiceImpl implements IQyEnterpriseService {
    @Autowired
    private QyEnterpriseMapper qyEnterpriseMapper;
    @Autowired
    private RemoteLeaseRecordService remoteLeaseRecordService;
    @Autowired
    private AllFeeProjectMapper allFeeProjectMapper;

    @Autowired
    private RemoteRoomService remoteRoomService;
    @Autowired
    private RemoteCustomerService customerService;

    @Autowired
    private RemoteSuretyService suretyService;


    @Autowired
    private IQyEnterpriseTypeService qyEnterpriseTypeService;

    /**
     * 查询企业概况
     *
     * @param id 企业概况ID
     * @return 企业概况
     */
    @Override
    public QyEnterprise selectQyEnterpriseById(String id) {
        QyEnterprise qyEnterprise = qyEnterpriseMapper.selectQyEnterpriseById(id);
        qyEnterprise.setFileList(getFileList(id));
//        FeLeaseRecord queryRecord = new FeLeaseRecord();
//        queryRecord.setEnterpriseId(id);
//        R<List<FeLeaseRecord>> listR = remoteLeaseRecordService.listRecord(queryRecord);
//        if (listR.getCode() == R.SUCCESS) {
//            listR.getData().forEach(leaseRecord -> {
//                R<List<RoomVO>> listR1 = remoteLeaseRecordService.selectRoomByRecordId(leaseRecord.getId());
//                if (listR1.getCode() == R.SUCCESS) {
//                    leaseRecord.setRoomVOList(listR1.getData());
//                }
//
//            });
//
//            qyEnterprise.setRecordList(listR.getData());
//        }
        return qyEnterprise;
    }

    /**
     * 查询企业概况列表
     *
     * @param qyEnterprise 企业概况
     * @return 企业概况
     */
    @Override
    public List<QyEnterprise> selectQyEnterpriseList(QyEnterprise qyEnterprise) {
        return qyEnterpriseMapper.selectQyEnterpriseList(qyEnterprise);
    }

    /**
     * 企业入驻
     *
     * @param qyEnterprise 企业概况
     * @return 结果
     */
    @Override
    public int insertQyEnterprise(QyEnterprise qyEnterprise) {
        qyEnterprise.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
        qyEnterprise.setCreateTime(DateUtils.getNowDate());
        qyEnterprise.setCreateBy(SecurityUtils.getUsername());
        linkFile(qyEnterprise.getFileIdList(), qyEnterprise.getId());
        FeFacility facility = initFacilityFe(qyEnterprise.getLeaseRecord().getFeFacility());


        FeLeaseRecord leaseRecord = qyEnterprise.getLeaseRecord();
        String feeId = IdUtil.getSnowflake(0, 0).nextIdStr();
        String leaseId = IdUtil.getSnowflake(0, 0).nextIdStr();
        leaseRecord.setId(leaseId);
        leaseRecord.getFeOffice().setId(feeId);
        leaseRecord.getFeProperty().setId(feeId);
        leaseRecord.getFeFacility().setId(feeId);
        leaseRecord.getFeProperty().setEnterpriseId(qyEnterprise.getId());
        if (leaseRecord.getFeProperty().getNextPropertyDate() == null) {
            leaseRecord.getFeProperty().setNextPropertyDate(leaseRecord.getFeProperty().getPropertyBeginDate());
        }
        if (leaseRecord.getNextRentDate() == null) {
            leaseRecord.setNextRentDate(leaseRecord.getRentBeginDate());
        }


        //保证金信息
        FeSurety feSurety = new FeSurety();
        feSurety.setId(feeId);
        feSurety.setEnterpriseId(qyEnterprise.getId());
        feSurety.setLeaseId(leaseId);
        feSurety.setSurety(leaseRecord.getSurety());
        feSurety.setDecorationSurety(leaseRecord.getDecorationSurety());
        feSurety.setSuretyDate(leaseRecord.getSuretyDate());

        suretyService.addSurety(feSurety);
        allFeeProjectMapper.insertFeOffice(leaseRecord.getFeOffice());
        allFeeProjectMapper.insertFeProperty(leaseRecord.getFeProperty());
        allFeeProjectMapper.insertFeFacility(facility);
        leaseRecord.setOfficeFeeId(feeId);
        leaseRecord.setPropertyFeeId(feeId);
        leaseRecord.setFacilityFeeId(feeId);
        if (leaseRecord != null) {
            leaseRecord.setEnterpriseId(qyEnterprise.getId());
            remoteLeaseRecordService.addLeaseRecord(leaseRecord);
        }

        if (StringUtils.isNotEmpty(qyEnterprise.getCustomerId())) {
            ZsCustomer zsCustomer = customerService.getCustomer(qyEnterprise.getCustomerId()).getData();
            zsCustomer.setSettledState("1");
            customerService.updateCustomer(zsCustomer);
        } else {
            ZsCustomer zsCustomer = new ZsCustomer();
            zsCustomer.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
            qyEnterprise.setCustomerId(zsCustomer.getId());
            zsCustomer.setEnterpriseName(qyEnterprise.getEnterpriseName());
            zsCustomer.setEnterpriseContact(qyEnterprise.getEnterpriseContact());
            zsCustomer.setContactPhone(qyEnterprise.getContactPhone());
            zsCustomer.setEnterType(qyEnterprise.getEnterType());
            zsCustomer.setEnterpriseType(qyEnterprise.getEnterpriseType());
            zsCustomer.setEnterpriseAddress(qyEnterprise.getAddress());
            zsCustomer.setSettledState("1");
            customerService.addCustomer(zsCustomer);
        }

        return qyEnterpriseMapper.insertQyEnterprise(qyEnterprise);
    }

    /**
     * 修改企业概况
     *
     * @param qyEnterprise 企业概况
     * @return 结果
     */
    @Override
    public int updateQyEnterprise(QyEnterprise qyEnterprise) {
        qyEnterprise.setUpdateTime(DateUtils.getNowDate());
        qyEnterprise.setUpdateBy(SecurityUtils.getUsername());
        linkFile(qyEnterprise.getFileIdList(), qyEnterprise.getId());
        FeLeaseRecord leaseRecord = remoteLeaseRecordService.getLeaseRecordByEnterprise(qyEnterprise.getId()).getData();
        if (leaseRecord != null) {
            remoteLeaseRecordService.updateLeaseRecord(leaseRecord);
        } else {
            leaseRecord.setEnterpriseId(qyEnterprise.getId());
            remoteLeaseRecordService.addLeaseRecord(leaseRecord);
        }
        return qyEnterpriseMapper.updateQyEnterprise(qyEnterprise);
    }

    /**
     * 批量删除企业概况
     *
     * @param ids 需要删除的企业概况ID
     * @return 结果
     */
    @Override
    public int deleteQyEnterpriseByIds(String[] ids) {
        //删除关联文件
        deleteLinkFile(ids);
        //删除租赁记录
        for (int i = 0; i < ids.length; i++) {
            remoteLeaseRecordService.delRecordByEnterpriseId(ids[i]);
        }
        return qyEnterpriseMapper.deleteQyEnterpriseByIds(ids);
    }


    /**
     * 删除企业概况信息
     *
     * @param id 企业概况ID
     * @return 结果
     */
    @Override
    public int deleteQyEnterpriseById(String id) {
        remoteLeaseRecordService.delRecordByEnterpriseId(id);
        return qyEnterpriseMapper.deleteQyEnterpriseById(id);
    }

    private FeFacility initFacilityFe(FeFacility feFacility) {
        String[] first = feFacility.getFirstFacilityFee().split("/");
        String[] second = feFacility.getSecondFacilityFee().split("/");
        String[] third = feFacility.getThirdFacilityFee().split("/");
        String[] fourth = feFacility.getFourthFacilityFee().split("/");
        String[] fifth = feFacility.getFifthFacilityFee().split("/");
        feFacility.setFirstYearFacilityFee(BigDecimal.valueOf(Double.parseDouble(first[0])));
        feFacility.setSecondYearFacilityFee(BigDecimal.valueOf(Double.parseDouble(second[0])));
        feFacility.setThirdYearFacilityFee(BigDecimal.valueOf(Double.parseDouble(third[0])));
        feFacility.setFourthYearFacilityFee(BigDecimal.valueOf(Double.parseDouble(fourth[0])));
        feFacility.setFifthYearFacilityFee(BigDecimal.valueOf(Double.parseDouble(fifth[0])));
        if (first.length > 1) {
            feFacility.setFirstYearTotal(BigDecimal.valueOf(Double.parseDouble(first[1])));
        } else {
            feFacility.setFirstYearTotal(BigDecimal.valueOf(Double.parseDouble(first[0])));
        }
        if (second.length > 1) {
            feFacility.setSecondYearTotal(BigDecimal.valueOf(Double.parseDouble(second[1])));
        } else {
            feFacility.setSecondYearTotal(BigDecimal.valueOf(Double.parseDouble(second[0])));
        }
        if (third.length > 1) {
            feFacility.setThirdYearTotal(BigDecimal.valueOf(Double.parseDouble(third[1])));
        } else {
            feFacility.setThirdYearTotal(BigDecimal.valueOf(Double.parseDouble(third[0])));
        }
        if (fourth.length > 1) {
            feFacility.setFourthYearTotal(BigDecimal.valueOf(Double.parseDouble(fourth[1])));
        } else {
            feFacility.setFourthYearTotal(BigDecimal.valueOf(Double.parseDouble(fourth[0])));
        }
        if (fifth.length > 1) {
            feFacility.setFifthYearTotal(BigDecimal.valueOf(Double.parseDouble(fifth[1])));
        } else {
            feFacility.setFifthYearTotal(BigDecimal.valueOf(Double.parseDouble(fifth[0])));
        }
        return feFacility;

    }


    private FeFacility initFacility(EnterpriseExcelVO o) {
        FeFacility feFacility = new FeFacility();
        feFacility.setId(IdUtil.getSnowflake(0, 0).nextIdStr());

        String[] first = o.getFirstYearFacilityFee().split("/");
        String[] second = o.getSecondYearFacilityFee().split("/");
        String[] third = o.getThirdYearFacilityFee().split("/");
        String[] fourth = o.getFourthYearFacilityFee().split("/");
        String[] fifth = o.getFifthYearFacilityFee().split("/");
        feFacility.setFirstYearFacilityFee(BigDecimal.valueOf(Double.parseDouble(first[0])));
        feFacility.setSecondYearFacilityFee(BigDecimal.valueOf(Double.parseDouble(second[0])));
        feFacility.setThirdYearFacilityFee(BigDecimal.valueOf(Double.parseDouble(third[0])));
        feFacility.setFourthYearFacilityFee(BigDecimal.valueOf(Double.parseDouble(fourth[0])));
        feFacility.setFifthYearFacilityFee(BigDecimal.valueOf(Double.parseDouble(fifth[0])));
        if (first.length > 1) {
            feFacility.setFirstYearTotal(BigDecimal.valueOf(Double.parseDouble(first[1])));
        } else {
            feFacility.setFirstYearTotal(BigDecimal.valueOf(Double.parseDouble(first[0])));
        }
        if (second.length > 1) {
            feFacility.setSecondYearTotal(BigDecimal.valueOf(Double.parseDouble(second[1])));
        } else {
            feFacility.setSecondYearTotal(BigDecimal.valueOf(Double.parseDouble(second[0])));
        }
        if (third.length > 1) {
            feFacility.setThirdYearTotal(BigDecimal.valueOf(Double.parseDouble(third[1])));
        } else {
            feFacility.setThirdYearTotal(BigDecimal.valueOf(Double.parseDouble(third[0])));
        }
        if (fourth.length > 1) {
            feFacility.setFourthYearTotal(BigDecimal.valueOf(Double.parseDouble(fourth[1])));
        } else {
            feFacility.setFourthYearTotal(BigDecimal.valueOf(Double.parseDouble(fourth[0])));
        }
        if (fifth.length > 1) {
            feFacility.setFifthYearTotal(BigDecimal.valueOf(Double.parseDouble(fifth[1])));
        } else {
            feFacility.setFifthYearTotal(BigDecimal.valueOf(Double.parseDouble(fifth[0])));
        }
        feFacility.setRentBeginDate(o.getFacilityBeginDate());
        feFacility.setRentEndDate(o.getFacilityEndDate());
        feFacility.setRentFreeBeginDate(o.getRentFreeBeginDate());
        feFacility.setRentFreeEndDate(o.getRentEndDate());
        feFacility.setNextRentDate(o.getFacilityNextRentDate());
        feFacility.setCalculationMode(o.getCalculationMode());
        feFacility.setPrice(o.getFacilityPrice());
        if ("1".equals(o.getEffect())) {
            feFacility.setEffect(1);
        } else {
            feFacility.setEffect(0);
        }


        return feFacility;

    }


    @Override
    public String importData(List<EnterpriseExcelVO> vos) {

        String msg = "";

        List<String> failRoom = new ArrayList<>();
        List<String> leas = new ArrayList<>();
        vos.stream().forEach(o -> {

            if (o.getEffect().equals("是")) {
                o.setEffect("1");
            } else {
                o.setEffect("0");
            }

            if (StringUtils.isNotBlank(o.getEnterpriseName())) {
                //查询企业是否存在
                QyEnterprise queryEnterprise = new QyEnterprise();
                queryEnterprise.setEnterpriseName(o.getEnterpriseName());
                List<QyEnterprise> list = qyEnterpriseMapper.selectQyEnterpriseList(queryEnterprise);
                QyEnterprise qyEnterprise = new QyEnterprise();
                if (list.size() == 0) {
                    //处理企业信息
                    BeanUtil.copyProperties(o, qyEnterprise);
                    qyEnterprise.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                    qyEnterprise.setCreateTime(DateUtils.getNowDate());
                    qyEnterprise.setCreateBy(SecurityUtils.getUsername());
                    String[] production = o.getProductionType().split("/");
                    qyEnterprise.setProductionType(StringUtils.join(production, ","));
                    //查询企业类型
                    QyEnterpriseType queryType = new QyEnterpriseType();
                    queryType.setEnterpriseType(qyEnterprise.getTypeId());
                    List<QyEnterpriseType> qyEnterpriseTypes = qyEnterpriseTypeService.selectQyEnterpriseTypeList(queryType);
                    if (qyEnterpriseTypes.size() > 0) {
                        qyEnterprise.setTypeId(qyEnterpriseTypes.get(0).getId());
                    } else {
                        qyEnterprise.setTypeId(null);
                    }
                } else {
                    qyEnterprise = list.get(0);
                }

                //房源租赁信息
                String[] rooms = o.getRooms().split("/");
                String[] areas = o.getRoomArea().split("/");
                String feeId = IdUtil.getSnowflake(0, 0).nextIdStr();
                FeLeaseRecord leaseRecord = new FeLeaseRecord();
                BeanUtil.copyProperties(o, leaseRecord);
                leaseRecord.setId(feeId);
                if (StringUtils.isBlank(o.getEffect()) || o.getEffect().equals("否")) {
                    leaseRecord.setEffect(0);
                } else {
                    leaseRecord.setEffect(1);
                }

                //保证金信息
                FeSurety feSurety = new FeSurety();
                feSurety.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                feSurety.setEnterpriseId(qyEnterprise.getId());
                feSurety.setLeaseId(feeId);
                feSurety.setSurety(o.getSurety());
                feSurety.setDecorationSurety(o.getDecorationSurety());
                feSurety.setSuretyDate(o.getSuretyDate());


                //租金信息
                FeOffice feOffice = new FeOffice();
                BeanUtil.copyProperties(o, feOffice);
                feOffice.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                feOffice.setPrice(o.getOfficePrice());
                leaseRecord.setFeOffice(feOffice);
                leaseRecord.setRecordType("0");

                //物业费用
                FeProperty property = new FeProperty();
                BeanUtil.copyProperties(o, property);
                property.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                if (("平方计费").equals(property.getFeeModel())) {
                    property.setFeeModel("1");
                } else {
                    property.setFeeModel("0");
                }
                property.setLeaseRecordId(leaseRecord.getId());
                property.setEnterpriseId(qyEnterprise.getId());


                //设施使用费
                FeFacility feFacility = initFacility(o);
                leaseRecord.setFeFacility(feFacility);
                leaseRecord.setOfficeFeeId(feOffice.getId());
                leaseRecord.setFacilityFeeId(feFacility.getId());
                leaseRecord.setPropertyFeeId(property.getId());


                for (int i = 0; i < rooms.length; i++) {
                    String room = rooms[i];
                    R<BuiRoom> r = remoteRoomService.getBuiRoomByNum(room);
                    if (r.getCode() == R.SUCCESS) {
                        if (r.getData().getLeaseState().equals("1")) {
                            //已经出租
                            log.error(room);
                            leas.add(room);
                        } else {
                            RoomVO rvo = new RoomVO();
                            rvo.setId(r.getData().getId());
                            if (areas.length > i) {
                                if (StringUtils.isNotBlank(areas[i])) {
                                    rvo.setContractArea(BigDecimal.valueOf(Double.parseDouble(areas[i])));
                                }
                            }
                            leaseRecord.getRoomVOList().add(rvo);
                            leaseRecord.getRoomIdList().add(r.getData().getId());
                        }
                    } else {
                        failRoom.add(room);
                    }
                }
                leaseRecord.setEnterpriseId(qyEnterprise.getId());
                if (leaseRecord.getRoomIdList().size() > 0) {
                    allFeeProjectMapper.insertFeOffice(leaseRecord.getFeOffice());
                    allFeeProjectMapper.insertFeFacility(leaseRecord.getFeFacility());

                    allFeeProjectMapper.insertFeProperty(property);

                    leaseRecord.setFeOffice(null);
                    leaseRecord.setFeFacility(null);
                    remoteLeaseRecordService.addLeaseRecord(leaseRecord);
                    suretyService.addSurety(feSurety);
                }
                R<ZsCustomer> r = customerService.getCustomerByName(qyEnterprise.getEnterpriseName());
                if (r.getCode() == R.SUCCESS) {
                    ZsCustomer zsCustomer = r.getData();
                    if (zsCustomer != null) {
                        zsCustomer.setSettledState("1");
                        customerService.updateCustomer(zsCustomer);
                    } else {
                        zsCustomer = new ZsCustomer();
                        zsCustomer.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                        qyEnterprise.setCustomerId(zsCustomer.getId());
                        zsCustomer.setEnterpriseName(qyEnterprise.getEnterpriseName());
                        zsCustomer.setEnterpriseContact(qyEnterprise.getEnterpriseContact());
                        zsCustomer.setContactPhone(qyEnterprise.getContactPhone());
                        zsCustomer.setEnterType(qyEnterprise.getEnterType());
                        zsCustomer.setEnterpriseType(qyEnterprise.getEnterpriseType());
                        zsCustomer.setEnterpriseAddress(qyEnterprise.getAddress());
                        zsCustomer.setSettledState("1");
                        customerService.addCustomer(zsCustomer);
                    }
                    qyEnterprise.setCustomerId(zsCustomer.getId());
                }
                if (list.size() == 0) {
                    qyEnterpriseMapper.insertQyEnterprise(qyEnterprise);
                }
            }
        });


        String leaMsg = "";
        for (String o : leas) {
            leaMsg = leaMsg + "," + o;
        }
        String failMsg = "";
        for (String o : failRoom) {
            failMsg = failMsg + "," + o;
        }
        if (StringUtils.isNotBlank(leaMsg)) {
            msg = msg + "房源：" + leaMsg + "已租赁，请检查\n";
        }
        if (StringUtils.isNotBlank(failMsg)) {
            msg = msg + "房源：" + failMsg + "不存在，请检查\n";
        }
        if (StringUtils.isBlank(msg)) {
            msg = "导入成功";
        }
        return msg;
    }

    @Override
    public String selectQyEnterpriseByName(String name) {
        QyEnterprise search = new QyEnterprise();
        search.setEnterpriseName(name);
        List<QyEnterprise> qyEnterprises = this.selectQyEnterpriseList(search);
        if(qyEnterprises != null && qyEnterprises.size()>0){
            return qyEnterprises.get(0).getId();
        }else{
            //insert qyEnterprise
            QyEnterprise qyEnterprise = new QyEnterprise();
            qyEnterprise.setEnterpriseName(name);
            this.insertSimpleQyEnterprise(qyEnterprise);
            return qyEnterprise.getId();
        }
        //return null;
    }

    @Override
    public int insertSimpleQyEnterprise(QyEnterprise qyEnterprise) {
        qyEnterprise.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
        qyEnterprise.setCreateTime(DateUtils.getNowDate());
        qyEnterprise.setCreateBy(SecurityUtils.getUsername());
        return qyEnterpriseMapper.insertQyEnterprise(qyEnterprise);
    }
}
